/**
 * Created by yx on 2017/7/20.
 */
// bootstrap 初始化
console.log("leaveMessage");

//全局变量，保存数据长度用于表格最后一条的向下按钮置灰
var dataLength = 0;

$("#message_table").bootstrapTable({
    // 'url': '../serviceType/findAll',
    'url': '/friends/commentsTemplate/findByContent',
    'toolbar': $('div[data-name="btnCtl"]'),
    'queryParams': queryParams,
    'cache':false,
    'sidePagination': 'server',
    'toolbarAlign': 'right',
    'undefinedText': '-',
    'striped': true,
    'pagination': true,
    'sortable': true, //是否启用排序
    'sortOrder': "asc", //排序方式
    'pageSize': globalPageSize,
    'pageList': [],
    'clickToSelect': true,
    'singleSelect': true,
    'smartDisplay': true,
    'ajaxOptions':{
        headers: {"Authorization": localStorage.token}
    },
    'responseHandler': function (resb) {
        console.log(resb);
        dataLength = resb.data.total;
        return {
            'total': resb.data.total,
            'rows': resb.data.content
        }
    },
    'onCheck': function() {
        $("button[data-target='#ForumInfoModal'],button[data-target='#commentModal'],button[data-target='#updateModal'], button[data-target='#deleteModal']").removeAttr("disabled");
    },
    'onUncheck': function() {
        $("button[data-target='#ForumInfoModal'],button[data-target='#commentModal'],button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
    },
    'onPageChange': function() {
        if($("#message_table").bootstrapTable('getSelections')[0]){
            $("#message_table").bootstrapTable('uncheckBy', {
                field: 'typeId',
                values: [$("#message_table").bootstrapTable('getSelections')[0].typeId]
            });
        }
    },
    'columns': [{
        'checkbox': true,
        // 'class': 'hide'
    },
        {
            'field': 'templateId',
            'title': '模板ID',
            'align': 'center',
            'class': 'hide id'
        },
        // {
        //     'title': '序号',
        //     'align': 'center',
        //     'formatter': function (value, row, index) {
        //         return index+1;
        //     }
        // } ,
        {
            'field': 'sort',
            'title': '排序',
            'align': 'center'
        }, {
            'field': 'content',
            'title': '模板内容',
            'width': 800,
            'align': 'center'

        },{
            'field': 'createTime',
            'title': '创建日期',
            'align': 'center',
            'sortable': true
        }, {
            'title': '操作',
            'align': 'center',
            'valign': 'middle',
            'formatter': function (value, row) {
                var html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up up' data-type='up' style='margin-right: 30px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down down' data-type='down'></button>";
                //将第一个tr的向上按钮置灰
                if (row.sort === 1) {
                    html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up up' disabled data-type='up' style='margin-right: 30px'></button><button class='btn btn-sm btn-success glyphicon glyphicon-arrow-down down' data-type='down'></button>";
                }
                if (row.sort === dataLength) {
                    html = "<button class='btn btn-sm btn-success glyphicon glyphicon-arrow-up up' data-type='up' style='margin-right: 30px'></button><button disabled class='btn btn-sm btn-success glyphicon glyphicon-arrow-down down' data-type='down'></button>";
                }
                return html;
            }
        }
    ]
});

//请求服务数据时所传参数
function queryParams(params){
    return {
        'content': $('#search-content').val(),
        offset: params.offset,
        limit : params.limit  //每一页的数据行数，默认是上面设置的10(pageSize)
    }
};

/**
 * 列表查询ajax
 * @param
 */
function leaveTempQuery() {
    if($("#search-content").val()== ''){
        $('#message_table').bootstrapTable('refreshOptions',{pageNumber:1,pageSize:globalPageSize});
    }else{
        var obj = {
            'content': $('#search-content').val(),
            'limit': 15,
            'offset': 0
        };
        $.ajaxSetup({cache:false});
        $.ajax({
            type: "GET",
            url: "/friends/commentsTemplate/findByContent?"+objTostring(obj),
            contentType: "application/json",
            dataType: 'json',
            // contentType: "application/json",
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", localStorage.token);
            },
            success: function(resb) {
                if (resb.data.length != 0) {
                    $("#message_table").bootstrapTable('load', {
                        'total': resb.data.total,
                        'rows': resb.data.content
                    });
                } else {
                    $("#message_table").bootstrapTable('removeAll');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    return false;
}

/**
 * 列表操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {roleId: int}]
 * @param async/scync [default async]
 */
function leaveMessage(action, data, async) {
    var url = null;
    (async === false) ? async = false: async = true;
    if (action === 'add') {
        url = '/friends/commentsTemplate/save?'+objTostring(data);
    } else if(action === 'update'){
        url = '/friends/commentsTemplate/update?'+objTostring(data);
    } else {
        url = '/friends/commentsTemplate/delete?'+objTostring(data);
    }
    return $.ajax({
        type: "GET",
        url: url,
        // data: JSON.stringify(data),
        contentType: "application/json",
        dataType: 'json',
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        async: async,
        success: function(resb) {
            alert(resb.message);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // console.log(XMLHttpRequest, textStatus, errorThrown);
            alert(textStatus);
        }
    });
}

function objTostring(obj) {
    var arr = [];
    for(var i in obj) {
        arr.push(i+"="+obj[i]);
    }
    return arr.join('&');
}

$(document).on('click','.spanIcons',function(){
    $('#inputStation').val("");
    if($('#inputStation').val() ==""){
        $('.spanIcons').removeClass('glyphicon glyphicon-remove');
    }
});
$("#inputStation").keyup(function(){
    if($('#inputStation').val() !=""){
        $('.spanIcons').addClass('glyphicon glyphicon-remove');
    }
    if($('#inputStation').val() ==""){
        $('.spanIcons').removeClass('glyphicon glyphicon-remove');
    }
});

//交换顺序
$('#message_table').off('click').on('click', '.up, .down', function () {
    var url = "/friends/commentsTemplate/sortMoveDown?templateId="+$(this).parent().siblings('.id').html();
    if($(this).attr('data-type') === 'up') {
        url = "/friends/commentsTemplate/sortMoveUp?templateId="+$(this).parent().siblings('.id').html();
    }
    $.ajax({
        type: "GET",
        url: url,
        contentType: "application/json",
        dataType: 'json',
        // contentType: "application/json",
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", localStorage.token);
        },
        success: function(resb) {
            if(resb.success) {
                $("#message_table").bootstrapTable("refresh");
            }else {
                alert(resb.message);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});

/**
 * 查询表单提交
 */
$("#dataSearch").on('click',function() {
    return leaveTempQuery();
});

// $("#selectClassify").change(function () {
//     return yuanfenQuery();
// });

//$("#stationFormId").submit(function() {
//    return yuanfenQueryByStationId($("#serviceProviderSel").val());
//});

/**
 * 新增模态框显示
 */
$("#addModal").on('show.bs.modal', function() {
    $(this).find("input[type=text]").val("");
});

/**
 * 修改模态框显示
 */
$("#updateModal").on('show.bs.modal', function() {
    $(this).find("input[type=text]").val("");
    var tableData = $("#message_table").bootstrapTable("getSelections")[0];
    $("#updateTemplateId").val(tableData.templateId);
    $("#updateContent").val(tableData.content);
});

/**
 * 删除模态框显示
 */
$("#deleteModal").on('show.bs.modal', function() {
    // var name = $("#message_table").bootstrapTable('getSelections')[0].name,
    var html = '是否删除当前模板?';
    $(this).find('div.modal-body').empty().append(html);
});

/**
 * 新增,更新,删除角色表单提交
 */
$("button[name=submit]").on('click',function() {
    var obj = $("#addForm, #updateForm").validationEngine('validate', {
        promptPosition: "centerRight",
        scroll: false,
        autoPositionUpdate: true,
        validationEventTrigger:'blur',
        binded:true,
        autoHidePrompt: true,
        autoHideDelay: 3000,
        showOneMessage:true
    });
    if (!obj) {
        return false;
    };
    var type = $(this).data("type"),
        $modal = $("#" + type + "Modal"),
        // $inputs = $modal.find('input[type="text"]'),
        // $selects = $modal.find('select'),


    //$checkboxs = $(this).find('input[type="checkbox"]').prop('checked',true),
       tableData = $("#message_table").bootstrapTable("getSelections")[0],
        data = null,
        $that = $(this);


    // 模式选择,设置不同的data和url
    if (type === 'delete') {
        data = {
            "templateId": tableData.templateId
        };
    } else if (type === 'add') {
        // var obj = jQuery("#addForm").validationEngine('validate', {promptPosition : "centerRight", autoPositionUpdate : true});
        // if(!obj){
        //     return false;
        // };
        data = {
            "content": $("#addContent").val()
            // "userId": $("#addUserId").val() === '' ? null : $("#addUserId").val()
        };
    } else if (type ==='update') {
        console.log(1)
        data = {
            "content": $("#updateContent").val(),
            "templateId": $("#updateTemplateId").val() === '' ? null : $("#updateTemplateId").val()
        };
    };


    $modal.modal('hide');
    // 完成ajax后刷新表格数据
    leaveMessage(type, data).done(function() {
        $("#message_table").bootstrapTable("refresh");
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
        $that.parents('.modal-content').find('form')[0].reset();
    });

    // 阻止表格冒泡事件
    return false;
});